package net.midnighttd.engine.entity.Pathfinder;

import net.midnighttd.engine.Engine;

/**
 * Author: Adam Scarr
 * Date: 21/04/2009
 * Time: 3:03:14 PM
 *
 * The pathfinder is used to find paths between points on the map. Because if its time consuming nature, it is done in
 * a seperate thread to improve responsiveness during pathfinding.
 */
public class Pathfinder implements Runnable {
    private Engine engine;
    private Thread pathfinderThread = new Thread(this, "Pathfinder");
    private boolean kill = false;
    private TaskQueue pathQueue = new TaskQueue();


    public Pathfinder(Engine game) {
        this.engine = game;

        pathfinderThread.start();
    }

    /**
     * The pathfinder thread will remain idle until jobs arrive for it to process.
     */
    public void run() {
        while(!kill) {
            try {
              Thread.sleep(1000000);
            } catch (InterruptedException ignored) {}

            emptyPathQueue();
        }
    }

    private void emptyPathQueue() {
        PathfinderTask task;
        while((task = pathQueue.poll()) != null) {
            task.run();
        }
    }

    public void stop() {
        kill = true;
        pathfinderThread.interrupt();
    }

    public void search(int startx, int starty, int endx, int endy, boolean flying, PathFoundListener callback) {
        PathfinderTask pathfinderTask = new PathfinderTask(engine, startx, starty, endx, endy, flying, callback);

        PathfinderTask existing = pathQueue.contains(pathfinderTask);
        if(existing != null) {
            existing.update(pathfinderTask);
        } else {
            pathQueue.add(pathfinderTask);
        }

        pathfinderThread.interrupt();
    }

    /**
     * Ok so sometimes you just need that path now.
     */
    public Path searchNow(int startX, int startY, int endX, int endY, boolean flying) {
        return new PathfinderTask(engine, startX, startY, endX, endY, flying).findPath();
    }
}
